<template>
  <div class="editInfo">
    <navBar
      :title="titleObj[type]"
      :path="path"
      :right="right"
      @rightClick="save"
    ></navBar>
    <div class="content">
      <van-field v-if="type !== 'avatar'" v-model="inputValue" class="filed" />
      <van-uploader
        v-else
        max-count="1"
        v-model="imgArr"
        :before-read="beforeRead"
        :after-read="afterRead"
        @delete="deleteEvent"
      />
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { auEdit, upload } from '@/api/my.js'
export default {
  data () {
    return {
      inputValue: '',
      right: '',
      type: this.$route.query.type, // 接收路由传递的参数
      path: '/home/myInfo',
      titleObj: {
        nickname: '修改昵称',
        intro: '修改个人简介',
        position: '修改岗位',
        avatar: '修改头像'
      },
      imgArr: []
    }
  },
  //
  computed: {
    ...mapState(['userInfo'])
  },
  created () {
    this.inputValue = this.userInfo[this.type]
    if (this.type === 'position') {
      this.path = '/home/my'
    }
    if (this.type === 'avatar' && this.userInfo.avatar) {
      this.imgArr[0] = { url: this.$baseUrl + this.userInfo.avatar }
    }
  },
  methods: {
    // 点击保存
    // 1.提示加载中
    // 2.调用接口修改资料
    // 3.提示成功
    // 4.跳转到myInfo页面
    // 5.刷新用户数据  也就是更新vuex中的数据
    async save () {
      this.$toast.loading({ duration: 0 })
      await auEdit({ [this.type]: this.inputValue })
      this.$toast.success('修改成功')
      this.$router.push(this.path)
      this.$store.dispatch('refreshUserInfo')
    },
    //  头像上传前
    beforeRead (file) {
      const _type = file.type === 'image/png' || file.type === 'image/jpeg'
      const _size = file.size / 1024 / 1024 < 2
      if (!_type) {
        this.$toast.fail('请上传png/jpeg格式图片')
      }
      if (!_size) {
        this.$toast.fail('请上传小于2Md的图片')
      }
      return _type && _size
    },
    // 头像读取后
    async afterRead (res) {
      const _formData = new FormData()
      this.$toast.loading({
        duration: 0,
        message: '上传中...'
      })
      _formData.append('files', res.file)
      const res2 = await upload(_formData)
      this.inputValue = res2.data.data[0].id
      this.$toast.success('上传成功')
      // console.log(res2)
    },
    // 删除头像触发
    deleteEvent () {
      this.inputValue = ''
    }
  },
  watch: {
    inputValue (newValue) {
      if (newValue !== this.userInfo[this.type] && newValue !== '') {
        this.right = '保存'
      } else {
        this.right = ''
      }
    }
  }
}
</script>
<style lang="less" scoped>
.editInfo {
  .content {
    padding: 34px @p15;
    text-align: center;
    .filed {
      background-color: #f7f4f5;
    }
  }
}
</style>
